package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.SetUserProfileReq;
import net.ib.mntalk.protocol.Session.SetUserProfileRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class SetUserProfileTask extends AsyncNetTask {
	
	private SetUserProfileReq mSetUserProfileReq;

	public SetUserProfileTask(Context _context, Handler _uiHandler, SetUserProfileReq setUserProfileReq) {
		super(_context, _uiHandler);
		this.mSetUserProfileReq = setUserProfileReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
		.setType(TcpEnvelope.REQUEST)
		.setMessage(mSetUserProfileReq)
		.setMethodId(Session.User.SetUserProfile)
		.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("SetUserProfilesTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		SetUserProfileRes setUserProfileRes = (SetUserProfileRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("SetUserProfilesTask ResponseCode : " + setUserProfileRes.getResponseCode());
		
		if(setUserProfileRes.getResponseCode() == Common.SUCCESS){
			if(mSetUserProfileReq.getProfile().getName() != null)
				GlobalPreferences.setUserName(mSetUserProfileReq.getProfile().getName().getFirstName());
			
			if(mSetUserProfileReq.getProfile() != null)
				GlobalPreferences.setUserStatus(mSetUserProfileReq.getProfile().getStatus());
			
			if(mSetUserProfileReq.getProfile().getProfileImage() != null)
				mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_USER_PROFILE_IMAGE_SUCCESS));
			else
				mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_USER_PROFILE_SUCCESS));
//			GlobalPreferences.setUserBirthday(mSetUserProfileReq.getProfile().getBirthday());
		} else {
			if(mSetUserProfileReq.getProfile().getProfileImage() != null)
				mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_USER_PROFILE_IMAGE_FAIL));
			else
				mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_SET_USER_PROFILE_FAIL));
		}
	}

}
